﻿using System;
using System.Security.Principal;
using System.Web;
using System.Web.Security;

namespace Services.Concrete
{
    public class CustomAuthentificationModule : IHttpModule
    {
        public void Init(HttpApplication httpAplication)
        {
            httpAplication.AuthenticateRequest += OnAuthenticateRequest;
        }

        private static void OnAuthenticateRequest(object sender, EventArgs e)
        {
            var application = (HttpApplication)sender;

            HttpContext context = application.Context;

            if (context.User != null && context.User.Identity.IsAuthenticated)
                return;

            string cookieName = FormsAuthentication.FormsCookieName;

            HttpCookie cookie = application.Request.Cookies[cookieName];

            if (cookie == null)
                return;

            try
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                var identity = new CustomIdentity(AccountEntry.Deserialize(ticket.UserData), ticket.Name);
                var principal = new GenericPrincipal(identity, identity.GetRoles());
                context.User = principal;
            }
            catch (Exception)
            {
            }
        }

        public void Dispose() { }
    }
}